package com.wendy.read.member.controller;

import com.wendy.read.common.utils.Result;
import com.wendy.read.member.pojo.User;
import com.wendy.read.member.utils.JwtUtil;
import com.wendy.read.member.utils.MD5Util;
import com.wendy.read.member.utils.ThreadLocalUtil;
import com.wendy.read.member.service.UserService;
//import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Validated
@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/findById")
    public User findById(Integer id){
        return userService.findById(id);
    }

    /**
     * 当前用户信息
     */
    @GetMapping("/userInfo")
    public Result<User> userInfo(){
        //获取业务信息
        Map<String, Object> map = ThreadLocalUtil.get();
        return Result.success(userService.findByUserName((String)map.get("username")));
    }

    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{6,16}$") String username,
                        @Pattern(regexp = "^\\S{6,16}$") String password){
        User user = userService.findByUserName(username);

        if (user == null){
            return Result.failure("用户名错误");
        }

        if (MD5Util.getMD5String(password).equals(user.getPassword())){
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", user.getId());
            claims.put("username", user.getUsername());
            String token = JwtUtil.getToken(claims);
            //
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token, token, 1, TimeUnit.HOURS);
            return Result.success(JwtUtil.getToken(claims));
        }
        return Result.failure("密码错误！");
    }

    /**
     * 用户注册
     * @param username 用户名
     * @param password 密码
     *
     */
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{6,16}$") String username,
                           @Pattern(regexp = "^\\S{6,16}$") String password){
        User user = userService.findByUserName(username);

        if (user == null){
            userService.register(username, password);
            return Result.success();
        }else {
            return Result.failure("用户名已被占用");
        }
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        userService.update(user);

        return  Result.success();
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return  Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params, @RequestHeader("Authorization") String token){
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.failure("缺少必要的参数！");
        }

        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");

        User loginner = userService.findByUserName(username);

        if (!loginner.getPassword().equals(MD5Util.getMD5String(oldPwd))){
            return Result.failure("原密码不正确！");
        }

        if (!rePwd.equals(newPwd)){
            return Result.failure("两次密码输入不一致！");
        }

        userService.updatePwd(newPwd, loginner.getId());
        //删除redis中的原token缓存
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);

        return Result.success();
    }
}
